<template>
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="true"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  
  <script setup>
  import { reactive, defineProps, defineEmits } from "vue";
  
  // 定义 Props
  const props = defineProps({
    title: {
      type: String,
      default: "数据导入",
    },
    url: {
      type: String,
      required: true,
    },
  });
  
  // 定义 Emits
  const emit = defineEmits(["success", "close"]);
  
  // 定义状态
  const upload = reactive({
    open: false, // 是否显示弹出层
    isUploading: false, // 是否正在上传
    headers: {}, // 请求头
  });
  
  // 打开对话框
  function openDialog() {
    upload.open = true;
  }
  
  // 关闭对话框
  function closeDialog() {
    upload.open = false;
    emit("close");
  }
  
  // 文件上传进度处理
  function handleFileUploadProgress(event) {
    upload.isUploading = true;
  }
  
  // 文件上传成功处理
  function handleFileSuccess(response) {
    upload.isUploading = false;
    emit("success", response); // 通知父组件上传成功
    closeDialog();
  }
  
  // 提交表单
  function submitFileForm() {
    if (uploadRef.value) {
      uploadRef.value.submit();
    }
  }
  
  // 暴露方法给父组件调用
  defineExpose({
    openDialog,
  });
  </script>
  
  <style scoped>
  .el-upload__tip {
    margin-top: 10px;
    font-size: 12px;
    color: #999;
  }
  .dialog-footer {
    text-align: right;
  }
  </style>